package isssr.bean.control;

import isssr.bean.entity.CurrentUser;
import isssr.bean.entity.User;
import isssr.bean.utility.EncryptionUtility;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

public class UserAuthenticationControl implements Serializable {

	/**
	 * 
	 */
	private static final String SUCCESS_URL 	= "login-success";
	private static final String FAILURE_URL 	= "login-failure";
	private static final long serialVersionUID 	= -4920920905514190679L;	
	
	
	public UserAuthenticationControl() {}
	

	
	public String login(String username, String password)
	{
		String ret_url 	= FAILURE_URL;
		//password 		= EncryptionUtility.getHexHashingString(password);
		User user 		= null;
		
		try {
			
			user = this.verifyUser(username, password);
			if(user != null)
			{
				this.createSession(user);
				ret_url = SUCCESS_URL;
			}
			
			else 
				this.sendMessage("Error", "Username or Password wrong!", FacesMessage.SEVERITY_ERROR);
		
		} catch (Exception e) {
			this.sendMessage("Error", "Username or Password wrong!", FacesMessage.SEVERITY_ERROR);
		}
		finally
		{
			return ret_url;
		}	
	}
	
	public String logout()
	{
		System.out.println("logout");
		FacesContext f_context =  FacesContext.getCurrentInstance();
		ExternalContext e_context = f_context.getExternalContext();
		e_context.invalidateSession();
	    
		return FAILURE_URL;
	}
	
	private User verifyUser(String username, String password) throws Exception
	{
		User user = new User();
		user.setUsername(username);
		user.setPassword(EncryptionUtility.getHexHashingString(password));
		Iterator it = user.loadSiblings();
		if(it.hasNext())
			user = (User) it.next();
		else 
			user = null;
		
		return user;
	}
		
	private void createSession(User u)
	{
		CurrentUser session_user = new CurrentUser();
		session_user.setUser(u);
		session_user.setAuthenticated(true);
		FacesContext f_context =  FacesContext.getCurrentInstance();
		ExternalContext e_context = f_context.getExternalContext();
		Map<String, Object> session_map = e_context.getSessionMap();
		session_map.put("currentUser", session_user);
	}
	
	private void sendMessage(String summary, String detail, Severity severity)
	{
		FacesMessage message = new FacesMessage(summary, detail);
		message.setSeverity(severity);
		FacesContext context = FacesContext.getCurrentInstance();  
		context.addMessage(null, message);  
	}
	
	
}
